from django.shortcuts import render, redirect, get_object_or_404
# from department.forms import DepartmentForm
from department.forms import DepartmentModelForm
from department.models import Department
from django.views.generic import ListView


# 判断部门名称是否已存在
def name_exist(name):
    is_exist = Department.objects.filter(name=name).exists()
    if is_exist:
        return True
    else:
        return False


# 添加数据
def create(request):
    form = DepartmentModelForm()
    if request.method == 'POST':
        msg = ''
        form = DepartmentModelForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get('name')
            if name_exist(name):
                form.add_error('name', "部门名称已存在,请确认!")
                msg = ''
            else:
                # department.save()
                form.save()
                msg = '恭喜你,创建部门信息成功!'
                # 重置表单内容(清空)
                form = DepartmentModelForm()  # 重置表单内容--清空
        return render(request, 'department/create.html',
                      {'form': form, 'msg': msg})
    else:
        return render(request, 'department/create.html', {'form': form})


# 修改数据
def update(request, depart_id):
    department = get_object_or_404(Department, pk=depart_id)
    if request.method == 'POST':
        msg = ''
        form = DepartmentModelForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get('name')
            # 如果部门名称进行了修改，需要判断是否重名
            if name != department.name and name_exist(name):
                form.add_error('name', "部门名称已存在,请确认!")
                msg = ''
            else:
                form.save()
                msg = '恭喜你,修改部门信息成功!'
        return render(request, 'department/update.html',
                      {'form': form, "depart_id": depart_id,
                       'msg': msg})
    else:
        form = DepartmentModelForm(instance=department)
        return render(request, 'department/update.html',
                      {'form': form, "depart_id": depart_id})


class DepartmentList(ListView):
    model = Department
    template_name = 'department/index.html'
    paginate_by = 5

    def get_queryset(self, *args, **kwargs):
        name = self.request.GET.get('name', '')
        if name != '':
            return Department.objects.filter(name=name).order_by('-createDate')
        else:
            return Department.objects.all().order_by('-createDate')

    def get_context_data(self, **kwargs):
        name = self.request.GET.get('name', '')
        context = super().get_context_data(**kwargs)
        context['name'] = name
        return context


# 删除数据
def delete(request, depart_id):
    department = get_object_or_404(Department, pk=depart_id)
    department.delete()
    return redirect('/department/')


# 详细信息
def detail(request, depart_id):
    department = get_object_or_404(Department, pk=depart_id)
    form = DepartmentModelForm(instance=department)
    return render(request, 'department/detail.html',
                  {'form': form, 'department': department})
